package com.fits.auth.api.component;

import cn.hutool.core.bean.BeanUtil;
import com.fits.auth.api.dto.SecurityUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        SecurityUser user = (SecurityUser) authentication.getPrincipal();
        //不能使用beanToMap，网关会报一个类型转换异常,估计是authorities字段类型的问题，其他地方需要String,这里用List生成的token会有类型转换异常问题
//        Map<String, Object> map = BeanUtil.beanToMap(user);
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", user.getClientId());
        map.put("user_name", user.getUsername());
        map.put("deptList", user.getDeptList());
        map.put("roleIdList", user.getRoleidsList());
        map.put("roleNameList", user.getRoleNameList());
        map.put("id", user.getId());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
        return accessToken;
    }
}
